package com.caocaog.market.common;

import com.caocaog.market.entity.PushMessageTemplate;
import com.caocaog.market.entity.PushTaskRecord;
import com.caocaog.market.entity.dto.PushAPIResultDTO;
import com.caocaog.market.service.PushTaskRecordService;
import com.getui.push.v2.sdk.common.ApiResult;
import com.getui.push.v2.sdk.dto.req.Audience;
import com.getui.push.v2.sdk.dto.req.AudienceDTO;
import com.getui.push.v2.sdk.dto.req.message.PushDTO;
import com.getui.push.v2.sdk.dto.res.TaskIdDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.Collections;
import java.util.Map;

@Slf4j
@Component
public class PushCommon {

    private PushTaskRecordService pushTaskRecordService;

    private static final String ERROR_DEFAULT_TASK_ID = "0";

    /**
     * 别名单推
     *
     * @param pushMessageTemplate 推送消息模版信息
     * @param alias                别名
     */
    public ApiResult<Map<String, Map<String, String>>> toSingleByAlias(PushMessageTemplate pushMessageTemplate, String alias) {
        PushDTO<Audience> pushDTO = PushUtils.buildPushDTO(pushMessageTemplate, alias);
        ApiResult<Map<String, Map<String, String>>> apiResult = PushUtils.pushApi.pushToSingleByAlias(pushDTO);
        PushTaskRecord pushTaskRecord = new PushTaskRecord()
                .setResponseResult(new PushAPIResultDTO<Map<String, Map<String, String>>>().convertFor(apiResult))
                .setPushMessageTemplateId(pushMessageTemplate.getId())
                .setTarget(Collections.singletonList(alias))
                .setCode(apiResult.getCode())
                .setPushType(2);

        if (apiResult.isSuccess()) {
            pushTaskRecord.setTaskId((String) apiResult.getData().keySet().toArray()[0]);
        } else {
            pushTaskRecord.setTaskId(ERROR_DEFAULT_TASK_ID);
        }
        this.pushTaskRecordService.addPushTaskRecord(pushTaskRecord);
        return apiResult;
    }

    /**
     * 创建消息
     * 此接口用来创建消息体，并返回taskId，为批量推的前置步骤。
     * 注：此接口频次限制200万次/天(和 {@link #toListByAlias 别名批量推} 共享限制)
     *
     * @param pushMessageTemplate 推送消息模版(title, content, payload)
     * @return taskId 任务id，用于执行cid批量推和执行别名批量推，此taskId不可多次使用，但可以给推送未成功的设备再推，有效期为用户设置的 {@link PushUtils#ttl 离线时间} （最多3天）
     */
    public ApiResult<TaskIdDTO> createMessage(PushMessageTemplate pushMessageTemplate) {
        ApiResult<TaskIdDTO> apiResult = PushUtils.pushApi.createMsg(PushUtils.buildPushDTO(pushMessageTemplate, (String) null));
        PushTaskRecord pushTaskRecord = new PushTaskRecord()
                .setResponseResult(new PushAPIResultDTO<TaskIdDTO>().convertFor(apiResult))
                .setPushMessageTemplateId(pushMessageTemplate.getId())
                .setCode(apiResult.getCode())
                .setPushType(5);

        if (apiResult.isSuccess()) {
            pushTaskRecord.setTaskId(apiResult.getData().getTaskId());
            this.pushTaskRecordService.addPushTaskRecord(pushTaskRecord);
        } else {
            pushTaskRecord.setTaskId(ERROR_DEFAULT_TASK_ID);
            this.pushTaskRecordService.addPushTaskRecord(pushTaskRecord);
        }
        return apiResult;
    }


    /**
     * 别名批量推
     * 对列表中所有别名进行消息推送。调用此接口前需调用 {@link #createMessage} 创建消息接口设置消息内容。
     * 注：此接口频次限制200万次/天(和 {@link #createMessage} 创建消息共享限制)
     *
     * @param pushMessageTemplateId 推送消息模版id
     * @param taskId                任务id
     * @param alias                 别名集
     */
    public ApiResult<Map<String, Map<String, String>>> toListByAlias(Integer pushMessageTemplateId, String taskId, String... alias) {
        AudienceDTO audienceDTO = PushUtils.buildAudienceDTO(taskId, alias);
        ApiResult<Map<String, Map<String, String>>> apiResult = PushUtils.pushApi.pushListByAlias(audienceDTO);
        PushTaskRecord pushTaskRecord = new PushTaskRecord()
                .setResponseResult(new PushAPIResultDTO<Map<String, Map<String, String>>>().convertFor(apiResult))
                .setPushMessageTemplateId(pushMessageTemplateId)
                .setTarget(Arrays.asList(alias))
                .setCode(apiResult.getCode())
                .setTaskId(taskId)
                .setPushType(7);

        if (apiResult.isSuccess()) {
            pushTaskRecord.setTaskId((String) apiResult.getData().keySet().toArray()[0]);
        } else {
            pushTaskRecord.setTaskId(ERROR_DEFAULT_TASK_ID);
        }
        this.pushTaskRecordService.addPushTaskRecord(pushTaskRecord);
        return apiResult;
    }


    @Autowired
    public void setPushTaskRecordService(PushTaskRecordService pushTaskRecordService) {
        this.pushTaskRecordService = pushTaskRecordService;
    }

}
